/*
 * FileName：AccountMenuCtrl.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.wx.wxcms.ctrl;

import java.util.Date;
import java.util.List;

import com.smart.common.BaseCtrl;
import com.smart.common.Constants;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smart.common.exception.WxErrorException;
import com.smart.common.util.AjaxResult;
import com.smart.common.util.WxMemoryCacheClient;
import com.smart.wx.common.util.wx.WxUtil;
import com.smart.wx.wxapi.process.MpAccount;
import com.smart.wx.wxapi.process.WxApi;
import com.smart.wx.wxapi.process.WxApiClient;
import com.smart.wx.wxapi.vo.Matchrule;
import com.smart.wx.wxcms.entity.AccountMenu;
import com.smart.wx.wxcms.entity.MsgBase;
import com.smart.wx.wxcms.service.AccountMenuService;
import com.smart.wx.wxcms.service.MsgBaseService;

/**
 * @author hermit
 * @version 2.0
 * @date 2018-04-17 10:54:58
 */
@Controller
@RequestMapping("/accountmenu")
public class AccountMenuCtrl extends BaseCtrl {
	@Autowired
	private AccountMenuService accountMenuService;
	@Autowired
	private MsgBaseService msgBaseService;

	@RequestMapping(value = "/list")
	@ResponseBody
	public AjaxResult list(AccountMenu accountMenu) {
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();
		accountMenu.setAccount(mpAccount.getAccount());
		List<AccountMenu> menus = accountMenuService.listWxMenus(accountMenu);
		Matchrule matchrule = new Matchrule();
		return AjaxResult.success(WxUtil.prepareMenus(menus, matchrule));
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public AjaxResult save(String menus) {
		JSONArray jsons = JSONArray.parseArray(menus);
		//每次先行删除公众号所有菜单
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();
		AccountMenu acm = new AccountMenu();
		acm.setAccount(mpAccount.getAccount());
		accountMenuService.delete(new AccountMenu());
		if (CollectionUtils.isNotEmpty(jsons)) {
			for (int i = 0; i < jsons.size(); i++) {
				JSONObject json = jsons.getJSONObject(i);
				if (null != json) {
					AccountMenu accountMenu = new AccountMenu();
					accountMenu.setAccount(mpAccount.getAccount());
//					String pid = CommonUtil.getUID();
//					accountMenu.setId(pid);
					accountMenu.setName(json.getString("name"));
					accountMenu.setSort(i + 1);
					accountMenu.setParentId((long) 0);
					if (json.containsKey("type")) {
						accountMenu.setMtype(json.getString("type"));
						//判断是否设置key
						if (Constants.MENU_NEED_KEY.contains(json.getString("type"))) {
							accountMenu.setEventType("fix");
							accountMenu.setMsgType(json.getString("msgType"));
							accountMenu.setMsgId(json.getString("msgId"));
						}
					}
					if (json.containsKey("url")) {
						accountMenu.setUrl(json.getString("url"));
					}
					if (json.containsKey("media_id")) {
						accountMenu.setMsgId(json.getString("media_id"));
					}
					if (json.containsKey("media_id")) {
						accountMenu.setMsgId(json.getString("media_id"));
					}
					if (json.containsKey("appid")) {
						accountMenu.setAppid(json.getString("appid"));
					}
					if (json.containsKey("pagepath")) {
						accountMenu.setPagepath(json.getString("pagepath"));
					}
					accountMenu.setCreateTime(new Date());
					//保存
					accountMenuService.add(accountMenu);
					//判断是否有subbutton
					if (json.containsKey("sub_button")) {
						JSONArray buttons = json.getJSONArray("sub_button");
						if (CollectionUtils.isNotEmpty(buttons)) {
							long pid = accountMenu.getId();
							for (int j = 0; j < buttons.size(); j++) {
								json = buttons.getJSONObject(j);
								accountMenu = new AccountMenu();
								accountMenu.setAccount(mpAccount.getAccount());
								accountMenu.setParentId(pid);
								accountMenu.setName(json.getString("name"));
								accountMenu.setSort(j + 1);
								if (json.containsKey("type")) {
									accountMenu.setMtype(json.getString("type"));
									//判断是否设置key
									if (Constants.MENU_NEED_KEY.contains(json.getString("type"))) {
										accountMenu.setEventType("fix");
										accountMenu.setMsgType(json.getString("msgType"));
										accountMenu.setMsgId(json.getString("msgId"));
									}
								}
								if (json.containsKey("url")) {
									accountMenu.setUrl(json.getString("url"));
								}
								if (json.containsKey("media_id")) {
									accountMenu.setMsgId(json.getString("media_id"));
								}
								if (json.containsKey("appid")) {
									accountMenu.setAppid(json.getString("appid"));
								}
								if (json.containsKey("pagepath")) {
									accountMenu.setPagepath(json.getString("pagepath"));
								}
								accountMenu.setCreateTime(new Date());
								accountMenuService.add(accountMenu);
							}
						}
					}
				}
			}
		}
		return AjaxResult.success();
	}

	@RequestMapping(value = "/syncMenu")
	@ResponseBody
	public AjaxResult syncMenu() throws WxErrorException {
		accountMenuService.delete(new AccountMenu());
		MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();
		String accessToken = WxApiClient.getAccessToken(mpAccount);
		JSONObject result = WxApi.queryMenu(accessToken);
		/**自定义菜单配置接口数据
		 * 通过接口创建的菜单，数据结构基本没变化，
		 * 通过原生后台创建的菜单，数据需要重新解析。
		 ***/
		//菜单是否开启selfmenu_info
		int isMenuOpen = result.getIntValue("is_menu_open");
		//如果开启再同步
		if (isMenuOpen == 1) {
			JSONArray menuArray = result.getJSONObject("selfmenu_info").getJSONArray("button");
			for (int i = 0; i < menuArray.size(); i++) {
				JSONObject button = menuArray.getJSONObject(i);//一级菜单
				JSONObject sub_button = button.getJSONObject("sub_button");

				AccountMenu pmenu = new AccountMenu();
				pmenu.setAccount(mpAccount.getAccount());
				pmenu.setParentId(0l);//一级菜单父ID为0
				pmenu.setName(button.getString("name"));
				pmenu.setCreateTime(new Date());
				pmenu.setSort(i + 1);
				if (null == sub_button || sub_button.isEmpty()) {
					//设置菜单
					setMenus(button, pmenu);
					accountMenuService.add(pmenu);//入库
				} else {
					//存在子菜单的
					JSONArray subMenus = sub_button.getJSONArray("list");//二级菜单-不一定存在
					accountMenuService.add(pmenu);//入库
					Long pid = pmenu.getId();//菜单父id
					for (int j = 0; j < subMenus.size(); j++) {
						AccountMenu smenu = new AccountMenu();
						smenu.setAccount(mpAccount.getAccount());
						smenu.setParentId(pid);//一级菜单ID

						smenu.setCreateTime(new Date());
						String sort = String.valueOf(i + 1) + String.valueOf(j + 1);
						smenu.setSort(Integer.parseInt(sort));
						JSONObject subMenu = subMenus.getJSONObject(j);//二级菜单

						smenu.setName(subMenu.getString("name"));
						setMenus(subMenu, smenu);
						accountMenuService.add(smenu);//二级菜单入库
					}
				}
			}
		}
		return AjaxResult.success();
	}

	/**
	 * 设置菜单
	 *
	 * @param button
	 * @param menu
	 */
	private void setMenus(JSONObject button, AccountMenu menu) {
		String mtype = button.getString("type");
		menu.setMtype(mtype);
		//除了view类型其他的都是都是回调事件
		if (mtype.equals("view")) {
			menu.setUrl(button.getString("url"));
		} else if (mtype.equals("miniprogram")) {//小程序
			menu.setAppid(button.getString("appid"));
			menu.setPagepath(button.getString("pagepath"));
			menu.setUrl(button.getString("url"));
		} else if (mtype.equals("media_id")) {//media_id类型菜单
			menu.setInputCode(button.getString("media_id"));//这里用code存储media_id
		}
		//原生后台创建的菜单数据解析开始=》
		else if (mtype.equals("news")
				|| mtype.equals("voice")
				|| mtype.equals("voice")
				|| mtype.equals("img")) {

			menu.setInputCode(button.getString("value"));//这里用code存储media_id

		} else if (mtype.equals("video")
				|| mtype.equals("text")) {
			//InputCode字段可能存不下这些数据-不作处理
			//menu.setInputCode(button.getString("value"));//这里用code存储文本内容和视频的url
		}
		//原生后台创建的菜单数据解析结束=《
		else {//其他类型菜单都存在‘key’
			String key = button.getString("key");
			if (key.indexOf("fix") != -1) {//证明是此后台创建的菜单
				String[] ks = key.split("fix_");
				menu.setEventType("fix");
				menu.setMsgId(ks[1]);
				MsgBase base = msgBaseService.getById(ks[1]);
				if (base != null) {
					menu.setMsgType(base.getMsgtype());
					menu.setInputCode(base.getInputcode());
				}
			} else {//证明不是此系统创建的菜单-key不插入本地数据库
//    					menu.setInputCode(key);//这里用code存储key
			}
		}
	}
}
